package com.shadowlight.hero_story.rank;

import com.alibaba.fastjson.JSONObject;
import com.shadowlight.hero_story.asyncOperation.AsyncOperation;
import com.shadowlight.hero_story.asyncOperation.IAsyncOperation;
import com.shadowlight.hero_story.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.resps.Tuple;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Consumer;

/**
 * @Description Rank排名服务
 * @Author cz
 * @Date 2022/3/22
 */
@Slf4j
public final class RankService {

    private RankService() {
    }

    private static final RankService RANK_SERVICE = new RankService();

    public static RankService getInstance() {
        return RANK_SERVICE;
    }

    public void getRankItemsFromRedis(Consumer<List<RankItem>> consumer) {

        AsyncOperation.getInstance().process(new IAsyncOperation() {

            private List<RankItem> rankItems = new ArrayList<>();

            @Override
            public void doAsync() {
                //从redis取出rankItems
                try (Jedis redis = RedisUtil.getRedis()) {

                    int rankId = 0;
                    List<Tuple> valueSet = redis.zrevrangeWithScores("RANK", 0, 9);
                    log.info("redis获取排名项:{}", Arrays.toString(valueSet.toArray()));

                    for (Tuple t : valueSet) {

                        int userId = Integer.parseInt(t.getElement());
                        int vin = (int) t.getScore();

                        String jsonStr = redis.hget("User_" + userId, "BasicInfo");
                        if (StringUtils.isEmpty(jsonStr)) continue;
                        JSONObject userInfo = JSONObject.parseObject(jsonStr);

                        rankItems.add(new RankItem(++rankId, userInfo.getInteger("id"),
                                userInfo.getString("userName"), userInfo.getString("heroAvatar"),
                                vin));
                    }
                }
            }

            @Override
            public void doFinish() {
                consumer.accept(rankItems);
            }
        });

    }

    /**
     * 刷新rank
     *
     * @param winnerId 赢家id
     * @param loserId  输家id
     */
    public void refreshRank(int winnerId, int loserId) {
        try (Jedis redis = RedisUtil.getRedis()) {
            //增加用户的输赢次数
            redis.hincrBy("User_" + winnerId, "Win", 1);
            redis.hincrBy("User_" + loserId, "Lose", 1);

            //看看赢家赢了多少次
            int winNum = Integer.parseInt(redis.hget("User_" + winnerId, "Win"));

            //更新到RANK
            redis.zadd("RANK", winNum, String.valueOf(winnerId));
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }

    }
}
